package com.cn.wanxi.servlet;

import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.model.PageModel;
import com.cn.wanxi.service.NewsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/newsPage")
public class NewsPage extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//      1.得到页面传递过来的值
        String type = req.getParameter("type");
        type = type == null ? "" : type;
        String pageNumStr = req.getParameter("pageNum");
        NewsService newsService = new NewsService();
        Integer pageNum = pageNumStr == null || "".equals(pageNumStr) ? 1 : Integer.parseInt(pageNumStr);
//        查询总条数
        Integer pageSize = 5;
        Integer count = newsService.findCount(new PageModel());
//        设置尾页
        Integer lastPage = 0;
        if (count % pageSize > 0) {
            lastPage = count / pageSize + 1;
        } else {
            lastPage = count / pageSize;
        }
        switch (type) {
            case "first":
                pageNum = 1;
                break;
            case "last":
                pageNum--;
                break;
            case "next":
                pageNum++;
//                如果下一页大于总页数，那么就是查询最后一页
                if (pageNum > lastPage) {
                    pageNum = lastPage;
                }
                break;
            case "end":
//                pageNum=//如果等于尾页，我们需要查询出总共有多少条，除以每一页显示的条数
//                假如总共有18条数据，每页显示10条数据
                pageNum = lastPage;
                break;
            default:
                break;

        }
        if (pageNum < 1)
            pageNum = 1;


//        2.分页封装条件语句
        PageModel pageModel = new PageModel();
        pageModel.setPageNum(pageNum);
        pageModel.setPageSize(pageSize);
        pageModel.setAllCount(count);
        pageModel.setAllPage(lastPage);
//        3.调用逻辑层

        List<NewsModel> list = newsService.findPage(pageModel);
        req.setAttribute("pageModel", pageModel);
        req.setAttribute("list", list);
//        4.页面转发
        req.getRequestDispatcher("/jsp/news.jsp").forward(req, resp);
    }
}
